﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using System.Windows.Controls;
using MyFloridaHouse.libSvCommonUtilities;
using MyFloridaHouse.libSvUtilities.Logging;
using MyFloridaHouse.libSvBingMapsMultiShape;
using MyFloridaHouse.libSvOpenDistricts.StorageIsolated;
using MyFloridaHouse.libSvUtilities;
using MyFloridaHouse.libSvOpenDistricts.enumerations;
using MyFloridaHouse.libSvOpenDistricts.Census;

namespace MyFloridaHouse.libSvOpenDistricts.Districts
{
    //// from districtPLanIO
    //public partial class DistrictPLan
    //{
    //    #region loadFile
    //    public void OpenDistrictPlan(string fileFormat, string districtPlanFileName, byte[] fileData)
    //    {
    //        bool loadSuccess = false;
    //        DistrictPlanFileLoadedEventArgs args = new DistrictPlanFileLoadedEventArgs();
    //        try
    //        {
    //            //if (fileFormat == Constants.PlanFileFormatInternal)
    //            //{
    //            //    args.loadType = enumDistrictPlanLoadType.LoadedShapeWKT;
    //            //    loadSuccess = LoadInternalFormatPlan(fileData);

    //            //}
    //            //else 
    //            if (fileFormat == Constants.PlanFileFormatFreds)
    //            {
    //                args.loadType = enumDistrictPlanLoadType.LoadedShapeUogIDs;
    //                loadSuccess = LoadFredsFormatPlan(districtPlanFileName, fileData);
    //            }
    //            else if (fileFormat == Constants.PlanFileFormatXML)
    //            {
    //                try
    //                {
    //                    xmlDistrictPlan = FromXML(fileData);
    //                    loadSuccess = true;
    //                }
    //                catch (Exception ex)
    //                {
    //                    loadSuccess = false;
    //                }
    //            }

    //            if (!loadSuccess)
    //            {
    //                Log.HandleInternalError("Unable to load selected district plan.");
    //            }
    //            else
    //            {
    //                RaiseDistrictPlanFileLoaded(args);
    //            }


    //        }
    //        catch (Exception ex)
    //        {
    //            ViewModelBase.RaiseNotifyUser("Unable to open district plan", ex);
    //        }
    //    }




    //    //todo: this needs to be moved to the district plan type class, and instead of caling ExtractPlanType, call static method on class
    //    private bool ExtractPlanType(string fileName, out string districtPlanTypeID, out int maxDistricts)
    //    {
    //        maxDistricts = 0;
    //        districtPlanTypeID = "";

    //        if (fileName.Length == 0)
    //        {
    //            ViewModelBase.RaiseNotifyUser("No file name found, file name must start with 'H'-house, 'C'-congress, 'S'-senate", null);
    //            return false;
    //        }

    //        string fileType = fileName.Substring(0, 1);
    //        if (fileType.ToUpper() == "H")
    //        {
    //            districtPlanTypeID = "HOU";
    //            maxDistricts = 120;
    //        }
    //        else if (fileType.ToUpper() == "S")
    //        {
    //            districtPlanTypeID = "SEN";
    //            maxDistricts = 40;
    //        }
    //        else if (fileType.ToUpper() == "C")
    //        {
    //            districtPlanTypeID = "CON";
    //            maxDistricts = 27;
    //        }
    //        else if (fileType.ToUpper() == "X")
    //        {
    //            districtPlanTypeID = "CUS";
    //            maxDistricts = 10;
    //        }
    //        else
    //        {
    //            ViewModelBase.RaiseNotifyUser("Invalid File Type, file name must start with 'H'-house, 'C'-congress, 'S'-senate 'X'-custom", null);
    //            return false;
    //        }
    //        return true;

    //    }

    //    private List<string> ExtractCondensedList(string fileText)
    //    {
    //        string[] lines = Regex.Split(fileText, "\r\n");
    //        List<string> condensedList = new List<string>();
    //        foreach (string line in lines)
    //        {
    //            condensedList.Add(line);
    //        }

    //        if (condensedList.Count == 0)
    //        {
    //            ViewModelBase.RaiseNotifyUser("Unable to load file, unable to extract condensed district list", null);
    //        }

    //        return condensedList;
    //    }




    //    #endregion
    //}


    //public partial class DistrictPlan
    //{

    //    public bool SaveIsolatedCanExecute(enumFileSaveFileSource fileSaveFileSource)
    //    {
    //        if (districtCount > 0)
    //        {
    //            if (fileSaveFileSource == enumFileSaveFileSource.LOCAL)
    //            {
    //                return false;
    //            }
    //            else
    //            {
    //                if (districtPlanFileName != null)
    //                {
    //                    if (districtPlanFileName.Length > 0)
    //                    {
    //                        return true;
    //                    }
    //                }
    //            }
    //        }
    //        return false;
    //    }

    //    SaveFileDialog textDialog;
    //    public void SaveLocalXML()
    //    {
    //        try
    //        {
    //            textDialog = new SaveFileDialog();
    //            textDialog.Filter = "District Plan(.xml) | *.xml";
    //            textDialog.DefaultExt = "xml";
    //            bool? result = textDialog.ShowDialog();
    //            if (result == true)
    //            {
    //                System.IO.Stream fileStream = textDialog.OpenFile();
    //                System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
    //                sw.Write(ToXML());
    //                sw.Flush();
    //                sw.Close();
    //            }

    //        }
    //        catch (Exception ex)
    //        {
    //            Log.HandleInternalError(ex.ToString());
    //        }
    //    }


    //    public void SaveIsolatedXML() //going to isolated storage
    //    {
    //        IsolatedStorageIncreaseDialog isolatedStorageIncreaseDialog = new IsolatedStorageIncreaseDialog();
    //        isolatedStorageIncreaseDialog.SaveToIsolatedStorageWithDialog(Constants.DistrictPlanDirectoryName, districtPlanFileName + Constants.DistrictPlanFileNameExtension, true, ToXML(), null);
    //    }

    //    public string ToXML()
    //    {
    //        try
    //        {
    //            PackXML();
    //            MemoryStream memstream = new MemoryStream();
    //            XmlSerializer xs = new XmlSerializer(typeof(DistrictPlan_XML));
    //            xs.Serialize(memstream, xmlDistrictPlan);
    //            memstream.Position = 0;
    //            StreamReader sr = new StreamReader(memstream);
    //            return sr.ReadToEnd();
    //        }
    //        catch(Exception ex)
    //        {
    //            // todo: log error converting to XML
    //            Log.HandleInternalError("Error converting district Plan to XML : " + ex.ToString());
    //            return "";
    //        }

    //    }


    //    public static DistrictPlan_XML FromXML(byte[] fileData)
    //    {
    //        MemoryStream xmlStream = new MemoryStream(fileData);
    //        XmlSerializer xs = new XmlSerializer(typeof(DistrictPlan_XML));
    //        return  (DistrictPlan_XML)xs.Deserialize(xmlStream);
    //    }


    //    public void PackXML()
    //    {
    //        List<string> condensedRegionList = censusGeometry.ToCondensedList(districtCount);

    //        xmlDistrictPlan = new DistrictPlan_XML();

    //        xmlDistrictPlan.planType = districtPlanTypeName;
    //        xmlDistrictPlan.numberOfDistricts = districtCount;
    //        xmlDistrictPlan.selectedDistrict = selectedDistrict;

    //        // load the district info
    //        // ignore district zero because all regions start out unassigned
    //        xmlDistrictPlan.districtList = new List<District_XML>();
    //        for (int ndx = 1; ndx < districtList.Count(); ndx++)
    //        {
    //            District_XML newXML = new District_XML();

    //            newXML.districtID = ndx;
    //            newXML.condensedRegionList = condensedRegionList[ndx];
    //            newXML.isLocked = districtList[ndx].isLocked;
    //            newXML.targetPopulation = districtList[ndx].targetPopulation;
    //            newXML.boundingBox = districtList[ndx].boundingBox;
    //            newXML.districtSubShapeList = new List<DistrictSubShapeMetadata>();
    //            foreach (var subShape in districtList[ndx].subShapeMetadataList)
    //            {
    //                newXML.districtSubShapeList.Add(subShape);
    //            }

    //            newXML.districtHoleList = new List<DistrictSubShapeMetadata>();
    //            foreach (var hole in districtList[ndx].subShapeHoleMetadataList)
    //            {
    //                newXML.districtHoleList.Add(hole);
    //            }
    //            xmlDistrictPlan.districtList.Add(newXML);

    //            MapMultiShapeBase shp = districtList[ndx].districtMultiMapShape;
    //            if (shp is MapMultiPolygon)
    //            {
    //                newXML.districtMultiMapShapeType = typeof(MapMultiPolygon).ToString();
    //                newXML.districtMultiMapShapeVertices = shp.Vertices.ToList();
    //            }
    //            else if (shp is MapMultiPolyline)
    //            {
    //                newXML.districtMultiMapShapeType = typeof(MapMultiPolyline).ToString();
    //                newXML.districtMultiMapShapeVertices = shp.Vertices.ToList();
    //            }
    //            else if (shp is MapMultiGeometry)
    //            {
    //                newXML.districtMultiMapShapeType = typeof(MapMultiGeometry).ToString();
    //                newXML.districtMultiMapShapeVertices = shp.Vertices.ToList();
    //            }
    //            else
    //            {
    //                Log.HandleInternalError("Can't save district shape, it is a " + shp.GetType().ToString());
    //            }
    //        }
    //    }

    //    public void UnPackXML()
    //    {

    //        //TODO: Need to convert plan type to plan typeID 
    //        InitializeDistrictPlan("", xmlDistrictPlan.numberOfDistricts, xmlDistrictPlan.planType.ToUpper(), xmlDistrictPlan.planType);

    //        censusGeometry.BypassLoadWithCondensed(xmlDistrictPlan.districtList);

    //        foreach (var xmlDistrict in xmlDistrictPlan.districtList)
    //        {
    //            int districtID = xmlDistrict.districtID;
    //            districtList[districtID].isLocked = xmlDistrict.isLocked;
    //            districtList[districtID].targetPopulation = xmlDistrict.targetPopulation;
    //            districtList[districtID].boundingBox = xmlDistrict.boundingBox;

    //            districtList[districtID].subShapeMetadataList = new List<DistrictSubShapeMetadata>();
    //            foreach (var subShape in xmlDistrict.districtSubShapeList)
    //            {
    //                districtList[districtID].subShapeMetadataList.Add(subShape);
    //            }

    //            districtList[districtID].subShapeHoleMetadataList = new List<DistrictSubShapeMetadata>();
    //            foreach (var hole in xmlDistrict.districtHoleList)
    //            {
    //                districtList[districtID].subShapeHoleMetadataList.Add(hole);
    //            }


    //            if (xmlDistrict.districtMultiMapShapeType == typeof(MapMultiPolygon).ToString())
    //            {
    //                districtList[districtID].districtMultiMapShape = new MapMultiPolygon();
    //                districtList[districtID].districtMultiMapShape.Vertices = xmlDistrict.districtMultiMapShapeVertices;
    //            }
    //            else if (xmlDistrict.districtMultiMapShapeType == typeof(MapMultiPolyline).ToString())
    //            {
    //                districtList[districtID].districtMultiMapShape = new MapMultiPolygon();
    //                districtList[districtID].districtMultiMapShape.Vertices = xmlDistrict.districtMultiMapShapeVertices;
    //            }
    //            else if (xmlDistrict.districtMultiMapShapeType == typeof(MapMultiGeometry).ToString())
    //            {
    //                districtList[districtID].districtMultiMapShape = new MapMultiGeometry();
    //                districtList[districtID].districtMultiMapShape.Vertices = xmlDistrict.districtMultiMapShapeVertices;
    //            }
    //            else
    //            {
    //                Log.HandleInternalError("Can't load district [" + districtID.ToString() + "] shape type [" + xmlDistrict.districtMultiMapShapeType + "]");
    //            }
    //        }

    //    }
    //}
}
